from sklearn.datasets import load_iris
from sklearn import preprocessing
from sklearn.decomposition import PCA
import numpy as np
import  pandas as pd
import matplotlib.pyplot as plt

class PCA:
    def __init__(self,n_components):
        self.n_components=n_components

    def fit_transform(self,X):
        zscore = preprocessing.StandardScaler()
        # 标准化处理M
        norm_X = zscore.fit_transform(X)
        norm_X=X
        mean = np.array([np.mean(norm_X[:, i]) for i in range(norm_X.shape[1])])
        norm_X = X - mean
        scatter_matrix = np.dot(np.transpose(norm_X), norm_X)/len(norm_X)
        lamda,v=np.linalg.eig(scatter_matrix)
        print(lamda)
        colum_index=np.argsort(lamda)>=X.shape[1]-self.n_components
        print(colum_index)
        reduced_X=[]
        for i in range(len(colum_index)):
            if colum_index[i]==True:  reduced_X=X[:,i].reshape((len(X),1)) if len(reduced_X)==0 else np.hstack((reduced_X,X[:,i].reshape((len(X),1))))
        return reduced_X


data=load_iris()
X=data.data
Y=data.target
pca=PCA(n_components=2)
reduced_X=pca.fit_transform(X)
color = ['r', 'b', 'g', 'y', 'bl']
print(X.shape)
df = pd.DataFrame(np.hstack((reduced_X,Y.reshape((len(Y),1)))))
for kClass, group in df.groupby(df.iloc[:, -1]):  # 根据某一列的值来聚类划分数据集，返回index
    plt.scatter(group.iloc[:,0],group.iloc[:,1],c=color[int(kClass)])
plt.show()